package net.tbao.authService.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import net.tbao.authService.fegin.MenberFeginService;
import net.tbao.authService.vo.SocialUserVo;
import net.tbao.common.constant.AuthServerContstant;
import net.tbao.common.utils.HttpUtils;
import net.tbao.common.utils.R;
import net.tbao.common.vo.MenberResponVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MenberFeginService menberFeginService;

    /**
     * 微博社交登录
     * @return
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String Weibo(@RequestParam("code")String code, HttpSession session, HttpServletResponse response) {

        Map<String, String> map= new HashMap<>();
        map.put("client_id","1981425959");
        map.put("client_secret","1f636ca6f9a329bcf00645fd743b9a08");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.tbao.cn/oauth2.0/weibo/success");
        map.put("code",code);
        //根据 code 换取 accessToken
        HttpResponse post = null;
        try {
            post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //处理  accessToken
        if(post.getStatusLine().getStatusCode()==200){
            String json = null;
            try {
                json = EntityUtils.toString(post.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);

            //登录 注册社交用户
            R r = menberFeginService.oauth2Login(socialUserVo);
            if (r.getCode() == 0) {
                MenberResponVO memberRespVo = r.getData("data", new TypeReference<MenberResponVO>() {
                });
                log.info("微博用户登录成功，用户信息：{}", memberRespVo);
                session.setAttribute(AuthServerContstant.LOGIN_USER, memberRespVo);
                return "redirect:http://tbao.cn";
            } else {
                return "redirect:http://auth.tbao.cn/login.html";
            }

        } else { // 远程请求社交服务获取数据失败
            return "redirect:http://auth.tbao.cn/login.html";
        }



    }
}
